﻿using Android.App;
using Android.Content;
using Android.OS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CoachingOrganizer.Android.Helpers
{
    public static class UIHelper
    {
        //try FragmentManager for later API
        private static readonly Dictionary<Guid, object> _activityModels = new Dictionary<Guid, object>();
        private const string UpperActivityBundleId = "Upper";

        private static Guid GetModelId<TModel>(TModel model)
        {
            Guid id = Guid.NewGuid();
            _activityModels.Add(id, model);
            return id;
        }

        public static TModel GetModelById<TModel>(Guid id)
        {
            return _activityModels.ContainsKey(id) ? (TModel)_activityModels[id] : default(TModel);
        }

        public static Intent GetIntent<TModel>(Activity sourceActivity, TModel targetModel, Type targetActivityType)
        {
            Intent intent = new Intent(sourceActivity, targetActivityType);
            Guid modelId = GetModelId(targetModel);
            intent.PutExtra(UpperActivityBundleId, modelId.ToString());
            return intent;
        }

        public static void GoActivity<TModel>(Activity sourceActivity, TModel targetModel, Type targetActivityType)
        {
            Intent intent = GetIntent(sourceActivity, targetModel, targetActivityType);
            sourceActivity.StartActivity(intent);
        }

        public static void GoResultActivity<TModel>(Activity sourceActivity, TModel targetModel, Type targetActivityType, int requestCode)
        {
            Intent intent = GetIntent(sourceActivity, targetModel, targetActivityType);
            sourceActivity.StartActivityForResult(intent, requestCode);
        }

        public static TModel GetActivityModel<TModel>(Activity currentActivity, Bundle bundle)
        {
            Guid modelId;
            if (!Guid.TryParse(currentActivity.Intent.GetStringExtra(UpperActivityBundleId), out modelId))
                return default(TModel);
            return GetModelById<TModel>(modelId);
        }
    }
}
